package com.nic.view.util;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;


/**
 * Created by Administrator on 2018/6/27.
 */

public class Utility {
    private final static String TAG = Utility.class.getSimpleName();

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

    public static void setListViewHeightBasedOnChildren(GridView listView) {
        // 获取listview的adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        // 固定列宽，有多少列
        int col = 3;// listView.getNumColumns();
        int totalHeight = 0;
        // i每次加4，相当于listAdapter.getCount()小于等于4时 循环一次，计算一次item的高度，
        // listAdapter.getCount()小于等于8时计算两次高度相加
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            // 获取listview的每一个item
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }

        // 获取listview的布局参数
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        // 设置高度
        params.height = totalHeight;
        // 设置margin
        ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10);
        // 设置参数
        listView.setLayoutParams(params);
    }


    /**
     * 计算出来的位置，y方向就在anchorView的上面和下面对齐显示，x方向就是与屏幕右边对齐显示
     * 如果anchorView的位置有变化，就可以适当自己额外加入偏移来修正
     *
     * @param windowPos   固定长度2  final int windowPos[] = new int[2];
     * @param anchorView  呼出window的view
     * @param contentView window的内容布局
     * @return window显示的左上角的xOff, yOff坐标
     */
    public static boolean calculatePopWindowPos(int[] windowPos, final View anchorView, final View contentView) {

        final int anchorLoc[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        anchorView.getLocationOnScreen(anchorLoc);
        final int anchorHeight = anchorView.getHeight();
        // 获取屏幕的高宽
        final int screenHeight = getScreenHeight(anchorView.getContext());
        final int screenWidth = getScreenWidth(anchorView.getContext());
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        // 计算contentView的高宽
        final int windowHeight = contentView.getMeasuredHeight();
        final int windowWidth = contentView.getMeasuredWidth();
        // 判断需要向上弹出还是向下弹出显示
        boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);
        if (isNeedShowUp) {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] - windowHeight;
        } else {
            windowPos[0] = screenWidth - windowWidth;
            windowPos[1] = anchorLoc[1] + anchorHeight;
        }
        return isNeedShowUp;
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static <T> Map<Integer, T> sortMapByKey(Map<Integer, T> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }

        Map<Integer, T> sortMap = new TreeMap<Integer, T>(
                comparator);

        sortMap.putAll(map);

        return sortMap;
    }

    static Comparator<Integer> comparator = new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            if (o1 > o2) {
                return 1;

            }
            if (o1 < o2) {
                return -1;
            }
            return 0;
        }
    };

    /**
     * @param map
     * @param format ","
     * @return
     */
    public static String mapKeyToString(Map<String, String> map, String format) {
        if (map == null || map.isEmpty()) {
            return "";
        }
        List<String> keys = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            keys.add(entry.getKey());
        }
        return TextUtils.join(format, keys);
    }

    public static String mapKeyToString(Map<String, String> map) {

        return mapKeyToString(map, ",");
    }

    /**
     * @param map
     * @param format "-"
     * @return
     */
    public static String mapValueToString(Map<String, String> map, String format) {
        if (map == null || map.isEmpty()) {
            return "";
        }

        List<String> values = new ArrayList<>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            values.add(entry.getValue());
        }
        return TextUtils.join(format, values);
    }

    public static String mapValueToString(Map<String, String> map) {
        return mapValueToString(map, "-");
    }

    /**
     * @param paths path1,path2,
     * @return
     */
    public static List<String> getListByDou(String paths) {
        List<String> list = new ArrayList<>();
        if (TextUtils.isEmpty(paths)) {
            return list;
        }
        for (String s : paths.split(",")) {
            if (!TextUtils.isEmpty(s)) {
                list.add(s);
            }

        }
        return list;
    }

    public List<String> getOperationList(String operation) {
        if (TextUtils.isEmpty(operation)) {
            return new ArrayList<>();
        } else {
            return new ArrayList<>(Arrays.asList(operation.split(",")));
        }
    }

    public static String getDouByList(List<String> list) {
        if (list.isEmpty()) {
            return "";
        }
        try {
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < list.size() - 1; i++) {
                stringBuffer.append(list.get(i) + ",");
            }
            return stringBuffer.substring(0, stringBuffer.length() - 1).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void disableSubControls(ViewGroup viewGroup) {
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            View v = viewGroup.getChildAt(i);
            v.setFocusable(false);
            if (v instanceof ViewGroup) {
                v.setEnabled(false);
                if (v instanceof Spinner) {
                    Spinner spinner = (Spinner) v;
                    spinner.setClickable(false);
                    spinner.setEnabled(false);
                    Log.i(TAG, "A Spinner is unabled");
                } else if (v instanceof ListView) {
                    ((ListView) v).setClickable(false);
                    ((ListView) v).setEnabled(false);
                    Log.i(TAG, "A ListView is unabled");
                } else {
                    disableSubControls((ViewGroup) v);
                }
            } else if (v instanceof EditText) {
                ((EditText) v).setEnabled(false);
                ((EditText) v).setClickable(false);
                Log.i(TAG, "A EditText is unabled");
            } else if (v instanceof Button) {
                ((Button) v).setEnabled(false);
                ((Button) v).setClickable(false);
//                Button button = (Button) v;
//                String text = button.getText().toString().trim();
//                if ("确认".equals(text) || "拍照".equals(text) || "完成".equals(text) || "返回".equals(text) || "保存".equals(text) || "提交".equals(text) || "取消".equals(text) || "上一步".equals(text) || "下一步".equals(text)) {
//                    button.setVisibility(View.GONE);
//                    viewGroup.setVisibility(View.GONE);
//                }
            } else if (v instanceof ImageView) {
                ((ImageView) v).setEnabled(false);
                ((ImageView) v).setClickable(false);
                Log.i(TAG, "A Button is unabled");
            } else if (v instanceof TextView) {
                ((TextView) v).setEnabled(false);
                ((TextView) v).setClickable(false);
//                TextView textView = (TextView) v;
//                String text = textView.getText().toString().trim();
//                if ("确认".equals(text) || "拍照".equals(text) || "完成".equals(text) || "返回".equals(text) || "保存".equals(text) || "提交".equals(text) || "取消".equals(text) || "上一步".equals(text) || "下一步".equals(text)) {
//                    textView.setVisibility(View.GONE);
//                    viewGroup.setVisibility(View.GONE);
//                }
            }
        }

    }

    public static void setEnableView(TextView textView) {
        textView.setEnabled(true);
        textView.setClickable(true);
        textView.setVisibility(View.VISIBLE);
    }

    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    public class RecyclerScrollListener extends RecyclerView.OnScrollListener {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
                mShouldScroll = false;
                smoothMoveToPosition(recyclerView, mToPosition);
            }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
        }
    }

    private static Utility utility;

    public static Utility getUtility() {
        if (utility == null) {
            return new Utility();
        }
        return utility;
    }

    public RecyclerScrollListener getRecyclerScrollListener() {
        return new RecyclerScrollListener();
    }

    public void showKeyboard(Context context) {
        try {
            InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void closeKeyboard(Context context) {
        try {
            View view = ((Activity) context).getWindow().peekDecorView();
            if (view != null) {
                InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setMargins(View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }

    /**
     * @param code 0,1
     * @param cbOk 0
     * @param cbNo 1
     */
    public static void previewState(String code, RadioButton cbOk, RadioButton cbNo) {
        if ("0".equals(code) || TextUtils.isEmpty(code)) {
            cbOk.setChecked(true);
        } else {
            cbNo.setChecked(true);
        }
        if (cbOk.isChecked()) {
            cbOk.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
            cbOk.setTextColor(0xFF4d4d4d);
            cbNo.setVisibility(View.INVISIBLE);
        } else {
            cbNo.setButtonDrawable(new ColorDrawable(Color.TRANSPARENT));
            cbNo.setTextColor(0xFF4d4d4d);
            cbOk.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 处理tag为空的情况
     *
     * @param v
     * @return
     */
    public static String convertTagToString(View v) {
        if (v.getTag() != null) {
            return v.getTag().toString();
        } else {
            return "";
        }
    }

    //删除指定文件夹下所有文件
    //param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    //删除文件夹
    //param folderPath 文件夹完整绝对路径
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setUnderlineBlueText(TextView textView, String text, ClickableSpan clickableSpan) {
        SpannableString spannableString = new SpannableString(text);
        spannableString.setSpan(new AbsoluteSizeSpan(14, true), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new ForegroundColorSpan(0xFF1883C7), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(new UnderlineSpan(), 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(clickableSpan, 0, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setMovementMethod(LinkMovementMethod.getInstance());
        textView.setText(spannableString);
    }

    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 获得状态栏的高度
     *
     * @param context
     * @return
     */
    public static int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 获取当前屏幕截图，包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 获取当前屏幕截图，不包含状态栏
     *
     * @param activity
     * @return
     */
    public static Bitmap snapShotWithoutStatusBar(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;

        int width = getScreenWidth(activity);
        int height = getScreenHeight(activity);
        Bitmap bp = null;
        bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
                - statusBarHeight);
        view.destroyDrawingCache();
        return bp;

    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */

    public static String getVersion(Context context) {
        try {
            // 获取管理器
            PackageManager manager = context.getPackageManager();
            // 获取数据
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            // 获取版本号
            String version = String.valueOf(info.versionCode);
            // 返回
            return version;

        } catch (Exception e) {
            return "0";
        }
    }

    /**
     * 计算两点之间距离(单位:米)
     *
     * @param long1
     * @param lat1
     * @param long2
     * @param lat2
     * @return
     */
    public static int getDistance(double long1, double lat1, double long2, double lat2) {
        double a, b, R;
        R = 6378137; // 地球半径
        lat1 = lat1 * Math.PI / 180.0;
        lat2 = lat2 * Math.PI / 180.0;
        a = lat1 - lat2;
        b = (long1 - long2) * Math.PI / 180.0;
        double d;
        double sa2, sb2;
        sa2 = Math.sin(a / 2.0);
        sb2 = Math.sin(b / 2.0);
        d = 2
                * R
                * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1)
                * Math.cos(lat2) * sb2 * sb2));
        String dStr = String.valueOf(d);
        return Integer.valueOf(dStr.substring(0, dStr.indexOf(".")));
    }


    /**
     * @param filePath 文件目录
     * @return boolean true为存在，false为不存在
     * @throws
     * @Methods: isFolderExist
     * @Description: 判断目录或者文件是否存在
     */
    public static boolean isFolderExist(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * @param file 删除的目标文件
     * @return 是否为正常的目录
     * @Methods: delete
     * @Description: 递归删除文件及文件夹 (删除)
     */
    public static boolean delete(File file) {
        if (file.isFile()) {
            file.delete();
            return false;
        }
        if (file.isDirectory()) {
            File[] childFiles = file.listFiles();
            if (childFiles == null || childFiles.length == 0) {
                file.delete();
                return false;
            }
            for (int i = 0; i < childFiles.length; i++) {
                delete(childFiles[i]);
            }
            file.delete();
        }
        return true;
    }

    /**
     * 文件转化为字节数组
     *
     * @param f 文件
     * @return 字节数组
     */
    public static byte[] getBytesFromFile(File f) {
        if (f == null) {
            return null;
        }
        try {
            FileInputStream stream = new FileInputStream(f);
            ByteArrayOutputStream out = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = stream.read(b)) != -1) {
                out.write(b, 0, n);
            }
            stream.close();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
        }
        return null;
    }

    /**
     * 四舍五入转化
     *
     * @param newScale 保留小数位数
     * @param value    转化的数值
     * @return 转化结果数据
     */
    public static String formatDecimals(int newScale, String value) {
        BigDecimal bd = new BigDecimal(value);
        String result = bd.setScale(newScale, RoundingMode.HALF_UP).toString();
        return result;
    }

    /**
     * 获取指定目录内所有文件路径
     *
     * @param fileList 放置文件路径的集合
     * @param dirPath  需要查询的文件目录
     * @param _type    查询类型，比如mp3什么的
     */
    public static void getAllFilesBySdcard(List<String> fileList, String dirPath, String _type) {
        File f = new File(dirPath);
        if (!f.exists()) {//判断路径是否存在
            return;
        }
        File[] files = f.listFiles();
        if (files == null) {//判断权限
            return;
        }
        for (File _file : files) {//遍历目录
            if (_file.isFile() && _file.getName().endsWith(_type)) {
//                String _name = _file.getName();
                String filePath = _file.getAbsolutePath();//获取文件路径
                fileList.add(filePath);
            } else {// if (_file.isDirectory())查询子目录
                getAllFilesBySdcard(fileList, _file.getAbsolutePath(), _type);
            }
        }
    }

    /**
     * 遍历指定目录下所有图片
     *
     * @param fileList 存放路径的集合，设置后填满路径再查询获得
     * @param dirPath
     */
    public static void getAllPhotoBySdcard(List<String> fileList, String dirPath) {
        File f = new File(dirPath);
        if (!f.exists()) {//判断路径是否存在
            return;
        }
        File[] files = f.listFiles();
        if (files == null) {//判断权限
            return;
        }
        for (File _file : files) {//遍历目录
            if (_file.isFile() && (_file.getName().endsWith(".jpg") || _file.getName().endsWith(".jpeg") || _file.getName().endsWith(".png"))) {
                String filePath = _file.getAbsolutePath();//获取文件路径
                fileList.add(filePath);
            } else {// if (_file.isDirectory())查询子目录
                getAllPhotoBySdcard(fileList, _file.getAbsolutePath());
            }
        }
    }
}
